import 'package:flutter/material.dart';

class Stagger extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('交织动画例子'),
      ),
      body: Center(
        child: StaggerAnimation(),
      ),
    );
  }
}

class StaggerAnimation extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _StaggerAnimationState();
  }
}

class _StaggerAnimationState extends State<StaggerAnimation> with SingleTickerProviderStateMixin {
  AnimationController _controller;
  Animation<double> _height;
  Animation<EdgeInsets> _padding;
  Animation<Color> _color;

  @override
  void initState() {
    super.initState();

    // 设置动画时长
    _controller = AnimationController(duration: Duration(seconds: 3), vsync: this);

    // 曲线定义，前后两段
    final _firstCurve = CurvedAnimation(
      parent: _controller,
      curve: Interval(
        0.0, 0.6, //间隔，前60%的动画时间
        curve: Curves.ease,
      ),
    );
    final _secondCurve = CurvedAnimation(
      parent: _controller,
      curve: Interval(
        0.6, 1.0, // 间隔，后40%的动画时间
        curve: Curves.ease,
      ),
    );

    // 高度动画
    _height = Tween<double>(begin: 0, end: 300).animate(_firstCurve);

    // 颜色动画
    _color = ColorTween(begin: Colors.green, end: Colors.red).animate(_firstCurve);

    // 左边距动画
    _padding = Tween<EdgeInsets>(begin: EdgeInsets.only(left: 0.0), end: EdgeInsets.only(left: 100)).animate(_secondCurve);

    // 自动正向执行一次
    _controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () async {
        try {
          // 先正向执行动画
          await _controller.forward().orCancel;
          // 再反向执行动画
          await _controller.reverse().orCancel;
        } on TickerCanceled {
          print('the animation got canceled, probably because we were disposed');
        }
      },
      child: Container(
        width: 300,
        height: 300,
        decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.1),
          border: Border.all(
            color: Colors.black.withOpacity(0.5),
          ),
        ),
        child: AnimatedBuilder(
          animation: _controller,
          builder: (BuildContext context, Widget child) {
            return Container(
              alignment: Alignment.bottomCenter,
              padding: _padding.value,
              child: Container(
                width: 50,
                height: _height.value,
                color: _color.value,
              ),
            );
          },
        ),
      ),
    );
  }

  @override
  void dispose() {
    // 销毁动画资源
    _controller.dispose();

    super.dispose();
  }
}